package cn.nfwx.tv.widget;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.Scroller;

import cn.nfwx.tv.util.LogUtil;

public class AutoAdjustRecylerView extends RecyclerView {

    private static final int TYPE_HORIZONTAL = 1;
    private static final int TYPE_VERTICAL = 2;


    private int type = TYPE_HORIZONTAL;

    private static final String TAG = "AutoAdjustRecylerView";
    private Scroller mScroller = null;
    private int mLastx = 1;
    //用于设置自动平移时候的速度
    private float mPxPerMillsec = 1000;

    private int mTargetPos;
    private boolean mIsRecording = false;

    private AutoAdjustRecylerViewListener adjustRecylerViewListener;

    public void setIsRecording(boolean mIsRecording) {
        this.mIsRecording = mIsRecording;
    }

    public AutoAdjustRecylerViewListener getAdjustRecylerViewListener() {
        return adjustRecylerViewListener;
    }

    public void setAdjustRecylerViewListener(AutoAdjustRecylerViewListener adjustRecylerViewListener) {
        this.adjustRecylerViewListener = adjustRecylerViewListener;
    }

    public interface AutoAdjustRecylerViewListener {
        void touchDown();

        void touchUp();
    }

    public AutoAdjustRecylerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initData(context);
    }

    public AutoAdjustRecylerView(Context context) {
        super(context);
        initData(context);
    }

    public AutoAdjustRecylerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initData(context);
    }

    private void initData(Context context) {
        if (mScroller == null) {
            mScroller = new Scroller(context, new DecelerateInterpolator());
        }
    }

    public void setScroller(Scroller scroller) {
        if (mScroller != scroller) {
            mScroller = scroller;
        }
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        if (TYPE_HORIZONTAL == type) {
            if (mScroller != null) {
                if (mScroller.computeScrollOffset())//如果mScroller没有调用startScroll，这里将会返回false。
                {
                    scrollBy(mLastx - mScroller.getCurrX(), 0);
                    mLastx = mScroller.getCurrX();
                    //继续让系统重绘
                    postInvalidate();
                }
            }
        } else if (TYPE_VERTICAL == type) {
            if (mScroller != null) {
                if (mScroller.computeScrollOffset())//如果mScroller没有调用startScroll，这里将会返回false。
                {
                    scrollBy(0, mLastx - mScroller.getCurrY());
                    mLastx = mScroller.getCurrY();
                    //继续让系统重绘
                    postInvalidate();
                }
            }
        }
    }


    @Override
    public boolean onInterceptTouchEvent(MotionEvent e) {
        if (e.getAction() == MotionEvent.ACTION_DOWN) {
            if (adjustRecylerViewListener != null) {
                adjustRecylerViewListener.touchDown();
            }
        } else if (e.getAction() == MotionEvent.ACTION_UP) {
            if (adjustRecylerViewListener != null) {
                adjustRecylerViewListener.touchUp();
            }
        }
        return super.onInterceptTouchEvent(e);
    }

    @Override
    public boolean onTouchEvent(MotionEvent e) {
        if (e.getAction() == MotionEvent.ACTION_DOWN) {
            if (adjustRecylerViewListener != null) {
                adjustRecylerViewListener.touchDown();
            }
        } else if (e.getAction() == MotionEvent.ACTION_UP) {
            if (adjustRecylerViewListener != null) {
                adjustRecylerViewListener.touchUp();
            }
        }
        return super.onTouchEvent(e);
    }

    public float getPxPerMillsec() {
        return mPxPerMillsec;
    }

    public void setPxPerMillsec(float pxPerMillsec) {
        this.mPxPerMillsec = pxPerMillsec;
    }

    public void checkAutoAdjust(int position) {
        if (mIsRecording) {
            return;
        }
        int parentWidth = getWidth();//获取父视图的宽度
        int childCount = getChildCount();//获取当前视图可见子view的总数
        //获取可视范围内的选项的头尾位置
        int firstvisiableposition = ((LinearLayoutManager) getLayoutManager()).findFirstVisibleItemPosition();
        int lastvisiableposition = ((LinearLayoutManager) getLayoutManager()).findLastVisibleItemPosition();
        int count = getLayoutManager().getItemCount();//获取item总数
        mTargetPos = Math.max(0, Math.min(count - 1, position));//获取目标item的位置（参考listview中的smoothScrollToPosition方法）
        View targetChild = getChildAt(mTargetPos - firstvisiableposition);//获取目标item在当前可见视图item集合中的位置
        View firstChild = getChildAt(0);//当前可见视图集合中的最左view
        View lastChild = getChildAt(childCount - 1);//当前可见视图集合中的最右view
        if (targetChild == null) {
            return;
        }
        if (lastChild == null) {
            return;
        }


        int childLeftPx = targetChild.getLeft();//子view相对于父view的左边距
        int childRightPx = targetChild.getRight();//子view相对于父view的右边距


        int childWidth = targetChild.getWidth();
        int centerLeft = parentWidth / 2 - childWidth / 2;//计算子view居中后相对于父view的左边距
        int centerRight = parentWidth / 2 + childWidth / 2;//计算子view居中后相对于父view的右边距

        if (!mIsRecording) {
            if (childLeftPx > centerLeft) {//子view左边距比居中view大（说明子view靠父view的右边，此时需要把子view向左平移
                //平移的起始位置就是子view的左边距，平移的距离就是两者之差
                autoAdjustScroll(childLeftPx, centerLeft);
            } else if (childRightPx < centerRight) {
                autoAdjustScroll(childRightPx, centerRight);
            }
        }
    }

    public void checkVerticalAutoAdjust(int position) {
        LogUtil.e(TAG, position + "");
        if (mIsRecording) {
            return;
        }
        int parentHeight = getHeight();//获取父视图的宽度
        int childCount = getChildCount();//获取当前视图可见子view的总数
        //获取可视范围内的选项的头尾位置
        int firstvisiableposition = ((LinearLayoutManager) getLayoutManager()).findFirstVisibleItemPosition();
        int count = getLayoutManager().getItemCount();//获取item总数
        mTargetPos = Math.max(0, Math.min(count - 1, position));//获取目标item的位置（参考listview中的smoothScrollToPosition方法）
        View targetChild = getChildAt(mTargetPos - firstvisiableposition);//获取目标item在当前可见视图item集合中的位置
        View firstChild = getChildAt(0);//当前可见视图集合中的最左view
        View lastChild = getChildAt(count - 1);//当前可见视图集合中的最右view
        if (targetChild == null) {
            return;
        }
        if (lastChild == null) {
            return;
        }


        int childTopPx = targetChild.getTop();//子view相对于父view的左边距
        int childBottomPx = targetChild.getBottom();//子view相对于父view的右边距


        int childHeight = targetChild.getHeight();
        int centerTop = parentHeight / 2 - childHeight / 2;//计算子view居中后相对于父view的左边距
        int centerBottom = parentHeight / 2 + childHeight / 2;//计算子view居中后相对于父view的右边距

        if (!mIsRecording) {
            if (childTopPx > centerTop) {//子view左边距比居中view大（说明子view靠父view的右边，此时需要把子view向左平移
                //平移的起始位置就是子view的左边距，平移的距离就是两者之差
                autoVerticalAdjustScroll(childTopPx, centerTop);
            } else if (childBottomPx < centerBottom) {
                autoVerticalAdjustScroll(childBottomPx, centerBottom);
            }
        }
    }

    /**
     * @param start 滑动起始位置
     * @param end   滑动结束位置
     */
    private void autoVerticalAdjustScroll(int start, int end) {
        type = TYPE_VERTICAL;
        mLastx = start;
        mScroller.startScroll(0, start, 0, end - start, 300);
        postInvalidate();
    }

    /**
     * @param start 滑动起始位置
     * @param end   滑动结束位置
     */
    private void autoAdjustScroll(int start, int end) {
        mLastx = start;
        mScroller.startScroll(start, 0, end - start, 0, 300);
        postInvalidate();
    }
}
